package com.linxi.handy.util;

import java.io.*;

/**
 * @PROJECT_NAME: MySQLva-gitee-lx
 * @DESCRIPTION:
 * @AUTHOR: lx
 * @DATE: 2022/3/11 14:18
 */
public class FileUtils {

    private final static String defaultEncoding = "utf-8";

    /**
     * read from file
     *
     * @param filePath
     * @return
     */
    public static String readContentFromFile(String filePath, String encoding) {
        File file = new File(filePath);
        try (InputStreamReader reader = new InputStreamReader(new FileInputStream(file), encoding)) {
            StringBuilder result = new StringBuilder();
            int flag;
            while ((flag = reader.read()) != -1) {
                result.append((char) flag);
            }
            return result.toString();
        } catch (IOException e) {
            LogUtil.log(e.getMessage());
            return "";
        }
    }

    public static boolean writeContentToFile(String filePath, String content) {
        // true表示不覆盖原来的内容，而是加到文件的后面。writer，直接省略这个参数就好
        try (FileWriter writer = new FileWriter(filePath, false)) {
            writer.write(content);
        } catch (IOException ex) {
            LogUtil.log(ex.getMessage());
            return false;
        }
        return true;
    }

    public static String readContentFromFile(String filePath) {
        return readContentFromFile(filePath, defaultEncoding);
    }
}
